package com.jinlejia.erp.ui.customer;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityEntering3Binding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.ActivityCollector;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.weight.IconToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 录带看第三步（activity）
 */

public class EnteringVisitActivity3 extends AppCompatActivity {

    JSONObject jsonObject = new JSONObject();
    private ProgressDialog progressDialog;
    private ActivityEntering3Binding binding;
    private String type,sex,name;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_entering3);
        ActivityCollector.addActivity2(this);
        binding.backBtn.setOnClickListener(this::onClick);
        binding.btUp.setOnClickListener(this::onClick);
        binding.btCommit.setOnClickListener(this::onClick);
        EventBus.getDefault().registerSticky(this);
        progressDialog = new ProgressDialog(this, "正在提交...");
        binding.inputContent.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = 200 - s.length();
                binding.textCount.setText(number + "/200");
                selectionStart = binding.inputContent.getSelectionStart();
                selectionEnd = binding.inputContent.getSelectionEnd();
                if (temp.length() > 200) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    binding.inputContent.setText(s);
                    binding.inputContent.setSelection(tempSelection);//设置光标在最后
                }
            }
        });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.bt_up:
                finish();
                break;
            case R.id.bt_commit:
                if(TextUtils.isEmpty(binding.inputContent.getText())){
                    CustomToast.showToast(EnteringVisitActivity3.this,"请输入带看总结",1500);
                }else{
                    jsonObject.put("summary",binding.inputContent.getText().toString());
                    submit();
                }
                break;
        }
    }
    @Subscriber(tag = "TAG_ENTER_DATA")
    private void data( Map<String,Object> map ){
        jsonObject.put("csCode",map.get("csCode").toString());
        type =  String.valueOf(map.get("type"));
        sex = String.valueOf(map.get("sex"));
        name = String.valueOf(map.get("name"));
        if( map.get("type").equals("sale") ){
            jsonObject.put("type",1);
        }else{
            jsonObject.put("type",0);
        }

        jsonObject.put("showStartTime",map.get("startTime").toString());
        jsonObject.put("showEndTime",map.get("endTime").toString());
        jsonObject.put("customerName",map.get("name").toString());
        ArrayList<Map<String, Object>> dataList = (ArrayList<Map<String, Object>>) map.get("houseList");
        JSONArray jsonArray = new JSONArray();
        for( Map<String, Object> m: dataList ){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("feedback",m.get("feedback"));
            jsonObject.put("houseType",m.get("houseType"));
            jsonObject.put("rscode",m.get("rscode"));
            jsonArray.add(jsonObject);
        }
        jsonObject.put("houseList",jsonArray.toString());
    }

    private void submit(){
        progressDialog.show();
        OkHttpUtils.postString()
                .url(ApiConfig.SAVE_VISIT)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(EnteringVisitActivity3.this, response)) {
                            //TODO 注意此处
//                            AppManger.getAppManager().finishActivity(EnteringVisitActivity1.class);
//                            AppManger.getAppManager().finishActivity(EnteringVisitActivity2.class);
                            IconToast.showToast(EnteringVisitActivity3.this,R.mipmap.common_ic_success,"保存成功",1500);
                            Intent intent = new Intent(EnteringVisitActivity3.this,DetailCustomerActivity.class);
                            intent.putExtra("csCode",String.valueOf(jsonObject.get("csCode")));
                            intent.putExtra("type",type);
                            intent.putExtra("sex",sex);
                            intent.putExtra("name",name);
                            intent.putExtra("daikan",true);
                            startActivity(intent);
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        ActivityCollector.removeActivity2(this);
        super.onDestroy();
    }
}
